package com.algorithm.standard;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;

public class QuarterShardingAlgorithm implements PreciseShardingAlgorithm<Timestamp> {


    public String getQuarter(String yearMonth ) {
        String year = yearMonth.substring(0, 4);
        String month = yearMonth.substring(5, 7);
        int intMonth = Integer.parseInt(month);
        int quarter = intMonth % 3 == 0 ? intMonth / 3 : intMonth / 3 + 1;

        String str = year + "0" + quarter;
        return str;
    }

    /**
     * 自定义分片规则 按季度分表
     *
     * @param collection
     * @param preciseShardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Timestamp> preciseShardingValue) {
        String logicTb = preciseShardingValue.getLogicTableName();
        String time = getQuarter(new SimpleDateFormat("yyyy-MM-dd").format(preciseShardingValue.getValue()));
        return logicTb + "_" + time;
    }
}
